package com.afeng.web.rest.interceptor;

import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.HandlerMapping;
import org.springframework.web.servlet.ModelAndView;

import com.afeng.web.rest.threadlocal.ParamsThreadlocal;

/**
 * 
 * @Title       : ParamsInterceptor
 * @Description : 请求参数封装拦截器
 * @Date        : 2017年11月14日
 * @author      : afeng
 */
@Component
public class ParamsInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
            throws Exception {
        Map<String, String> params = new HashMap<>();
        Map<String, String[]> requestParams = request.getParameterMap();
        // 获取request中的参数，取第一个值
        for (String key : requestParams.keySet()) {
            String[] value = requestParams.get(key);
            params.put(key, value[0]);
        }
        @SuppressWarnings("unchecked")
        Map<String, String> pathVariables = (Map<String, String>) request
                .getAttribute(HandlerMapping.URI_TEMPLATE_VARIABLES_ATTRIBUTE);
        // 获取path中的参数
        for (String key : pathVariables.keySet()) {
            String value = pathVariables.get(key);
            params.put(key, value);
        }
        ParamsThreadlocal.PARAMS.set(params);
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
            ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
            throws Exception {
        ParamsThreadlocal.PARAMS.remove();
    }

}
